package com.mark.operator.crd;

import com.mark.operator.AppType;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@ControllerConfiguration
public class RestartPolicyReconciler implements Reconciler<RestartPolicy> {
    private final KubernetesClient kubernetesClient;

    @Override
    public UpdateControl<RestartPolicy> reconcile(RestartPolicy restartPolicy, Context<RestartPolicy> context) throws Exception {
        AppType appType = restartPolicy.getSpec().getAppType();
        String appName = restartPolicy.getSpec().getAppName();
        String namespace = restartPolicy.getMetadata().getNamespace();
        if (AppType.DEPLOYMENT == appType) {
            Deployment deployment = kubernetesClient.apps().deployments().inNamespace(namespace).withName(appName).get();
            Map<String, String> annotations = deployment.getSpec().getTemplate().getMetadata().getAnnotations();
            annotations.put("restart", LocalDateTime.now().toString());
            deployment.getSpec().getTemplate().getMetadata().setAnnotations(annotations);
            deployment.edit()
                    .editSpec()
                    .editTemplate()
                    .editMetadata()
                    .addToAnnotations("restart", LocalDateTime.now().toString())
                    ;

        }
        return UpdateControl.updateResource(restartPolicy);
    }
}
